﻿using BW.WMS.CodeEnum;
using BW.WMS.RBAC;
using BW.WMS.XKY.DTO.Input;
using BW.WMS.XKY.DTO.Output;
using MD5Hash;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace BW.WMS.XKY
{
    public class UserAppService : ApplicationService, IUserAppService
    {
        private readonly IRepository<UserModel,Guid> _userRepository;
        private readonly IRepository<RoleModel, Guid> _roleRepository;

        public UserAppService(IRepository<UserModel, Guid> userRepository, IRepository<RoleModel, Guid> roleRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
        }

        public async Task<ApiResult<int>> CreateAsync(UserInput input)
        {
            var user = ObjectMapper.Map<UserInput, UserModel>(input);
            user.Password = user.Password.GetMD5();
            await _userRepository.InsertAsync(user);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Success,
                Data = 1,
                Message = "添加成功"
            };
        }

        public Task<ApiResult<int>> DeleteAsync(Guid id)
        {
            throw new NotImplementedException();
        }

        public Task<IQueryable<ApiPaging<UserOutput>>> GetListAsync()
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResult<UserOutput>> LoginAsync(string? UserNameOrEmail, string Pwd)
        {
            var user =await _userRepository.GetAsync(x => x.UserName == UserNameOrEmail || x.Email == UserNameOrEmail);
            if (user == null)
            {
                return new ApiResult<UserOutput>()
                {
                    Code = ApiEnum.Fail,
                    Data = null,
                    Message = "用户不存在"
                };
            }
            else 
            {
                Pwd=Pwd.GetMD5();
                if (user.Password!= Pwd)
                { 
                    return new ApiResult<UserOutput>()
                    {
                        Code = ApiEnum.Fail,
                        Data = null,
                        Message = "密码错误"
                    };
                }
            }
            var role = await _roleRepository.GetAsync(x => x.Id == user.RoleId);
            var output = ObjectMapper.Map<UserModel, UserOutput>(user);
            output.RoleName = role.RoleName;
            return new ApiResult<UserOutput>() 
            {
                Code=ApiEnum.Success,
                Data=output,
                Message="登录成功"
            };
        }

        public Task<ApiResult<int>> UpdateAsync(Guid id, UserInput input)
        {
            throw new NotImplementedException();
        }
    }
}
